package com.book.controller;

import com.book.dto.ShopCarDto;
import com.book.dto.UserDto;
import com.book.remote.ShopCarRemote;
import com.book.util.Constants;
import com.book.vo.ShopCarVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author 李锦程
 * @Date 2021/4/22 6:55 下午
 * @Package com.book.controller
 * @Version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/shop")
public class ShopCarController {
    @Autowired
    private ShopCarRemote carService;

    @RequestMapping("/car/index")
    public String getCarDetail(HttpSession session, Model model) {
        UserDto user = (UserDto) session.getAttribute("user");
        ShopCarDto carByUId = carService.getCarByUId(user.getId());
        if (carByUId == null){
            return "error-404.jsp";
        }
        List<ShopCarVo> shopCarDetail = carService.getShopCarDetail(carByUId.getScCode());
        model.addAttribute("cars", shopCarDetail);
        return "car/index.jsp";
    }

    @RequestMapping("/car/add")
    @ResponseBody
    public String Save(String ubCode, HttpSession session) {
        UserDto userDto = (UserDto) session.getAttribute("user");
        ShopCarDto shopCarCode = carService.getCarByUId(userDto.getId());
        if (shopCarCode == null) {
            ShopCarDto carDto = new ShopCarDto();
            carDto.setUId(userDto.getId());
            carDto.setScCode(userDto.getUCode());
            carService.addCar(carDto);
        }
        return carService.addBookToCar(ubCode, userDto.getUCode());
    }

    @RequestMapping("/car/numAdd")
    @ResponseBody
    public String NumAdd(Integer id) {
        try {
            carService.updateCarBookNum(id, 1);
            return Constants.SUCCESS;
        } catch (Exception e) {
            log.error("ShopCarController.NumAdd#id:{}", id, e);
            return Constants.ERROR;
        }
    }

    @RequestMapping("/car/numSub")
    @ResponseBody
    public String NumSub(Integer id) {
        try {
            carService.updateCarBookNum(id, -1);
            return Constants.SUCCESS;
        } catch (Exception e) {
            log.error("ShopCarController.NumSub#id:{}", id, e);
            return Constants.ERROR;
        }
    }

    @RequestMapping("/car/delete")
    @ResponseBody
    public String Delete(Integer id) {
        try {
            Integer integer = carService.deleteCarBook(id);
            return integer == 1 ? Constants.SUCCESS : Constants.ERROR;
        } catch (Exception e) {
            log.error("ShopCarController.Delete#id:{}", id, e);
            return Constants.ERROR;
        }
    }
}
